import asyncio
import json
import multiprocessing
import os
import pickle
import platform
from importlib import import_module
from app import create_app
from utils.redis_utils import setup_redis, close_redis
from dotenv import load_dotenv
import lightgbm as lgb

if platform.system() != "Windows":
    import uvloop
    asyncio.set_event_loop_policy(uvloop.EventLoopPolicy())
else:
    import nest_asyncio
    nest_asyncio.apply()

load_dotenv(verbose=True)

# 配置读取的配置文件
# SETTINGS_MODULE = "conf.prod"
SETTINGS_MODULE = "conf.secret"
Config = import_module(SETTINGS_MODULE)

app = create_app(Config)

# `workers` is num of subprocesses 
def get_workers():
    if not app.config.DEBUG and platform.system() != "Windows":
        return multiprocessing.cpu_count()
    return 2

@app.listener("before_server_start")
async def setup(app, loop):
    await setup_redis(app, loop)
    await load_models(app, loop)
    
async def load_models(app, loop):
    app.state.models = {}
    app.state.jsons = {}
    
    # 遍历项目中所有名为 "model" 的文件夹
    for root, dirs, files in os.walk(os.getcwd()):
        if "model" in root:
            for file in files:
                if file.endswith(".pkl"):
                    model_path = os.path.join(root, file)
                    with open(model_path, "rb") as f:
                        # model_name = os.path.splitext(file)[0]
                        model_name = str(file)
                        app.state.models[model_name] = pickle.load(f)
                        print(f"Loaded model (pkl): {model_name}")
                if file.endswith(".json"):
                    file_path = os.path.join(root, file)
                    with open(file_path, "rb") as f:
                        model_name = str(file)
                        app.state.jsons[model_name] = json.load(f)
                        print(f"Loaded json file: {model_name}")
                # if file.endswith(".model"):
                #     model_path = os.path.join(root, file)
                #     with open(model_path, "rb") as f:
                #         model_name = os.path.splitext(file)[0]
                #         app.state.models[model_name] = lgb.Booster(model_file=model_path)
                #         print(f"Loaded model (model): {model_name}")

@app.listener("after_server_stop")
async def cleanup(app, loop):
    await close_redis(app, loop)


if __name__ == "__main__":
    
    print(app.config.REDIS_URL)
    print(app.config.DB_URL)
    
    app.run(
        host="0.0.0.0",
        port=8000,
        debug=app.config.DEBUG,
        access_log=app.config.ACCESS_LOG,
        workers=get_workers(),
        auto_reload=app.config.AUTO_RELOAD,
    )
